package cn.itcast.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.tanhua.dubbo.server.enums.IdType;
import cn.itcast.tanhua.dubbo.server.pojo.FollowUser;
import cn.itcast.tanhua.dubbo.server.pojo.Video;
import cn.itcast.tanhua.dubbo.server.service.IdService;
import cn.itcast.tanhua.dubbo.server.vo.PageInfo;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName VideoApiImpl
 * @Description 小视频功能实现
 * @Author WU
 * @Date 2021/6/2 17:07
 * @Version 1.0
 */
@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //  指定redisKey的前缀
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 发布小视频
     *
     * @return java.lang.String
     * @Param video
     */
    @Override
    public String saveVideo(Video video) {
        try {
//        校验视频内容，发布人id，封面路径及视频路径必须得有
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                //            没有则返回空
                return null;
            }
//        设置id
            video.setId(ObjectId.get());
            video.setVid(this.idService.createId(IdType.VIDEO));

//        发布时间
            video.setCreated(System.currentTimeMillis());

//        保存到MongoDB中
            this.mongoTemplate.save(video);
//            将视频id返回
            return video.getId().toHexString();

        } catch (Exception e) {
//            异常则记录日志
            log.error("小视频发布失败~ video = " + video, e);
        }

        return null;
    }


    /**
     * 分页查询小视频，先查询redis中的推荐视频，有需要再查询MongoDB中存的视频
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return PageInfo<Video>
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
//        将分页参数放入PageInfo
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

//       从redis中查询推荐视频id
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
//        判断有没有查到推荐视频，有的话则进行手动分页，并将视频id放入集合
        int recommendCount = 0;
        List<Long> vids = new ArrayList<>();
        if (StrUtil.isNotEmpty(redisData)) {
            List<String> vidList = StrUtil.split(redisData, ',');
//            将分页参数放入数组
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
//            设置起点索引和终点索引
            int startIndex = startEnd[0];
//            比较页面显示条数和推荐视频数量，取小的作为终点索引
            int endIndex = Math.min(startEnd[1], vidList.size());
//            将视频路径按索引顺序取出并放入集合
            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
//            获取推荐视频的数量
            recommendCount = vidList.size();
        }
//        如果推荐视频的数量满足不了查询的数量，则查询MongoDB中存的视频
        if (CollUtil.isEmpty(vids)) {
//            计算推荐视频占用的查询页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);

//            分页查询MongoDB中的视频数据，按时间倒序排列
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
//            将视频列表放入PageInfo
            pageInfo.setRecords(videoList);
            return pageInfo;
        }
//        根据集合中的推荐视频id查询推荐视频，redis中仅存了要推荐的视频id，视频保存在MongoDB中
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = this.mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);

        return pageInfo;
    }

    /**
     * 根据id，调用dubbo查询单个视频
     *
     * @param publishId
     * @return cn.itcast.tanhua.dubbo.server.pojo.Video
     */
    @Override
    public Video queryVideoById(String publishId) {
        return this.mongoTemplate.findById(new ObjectId(publishId), Video.class);
    }

    /**
     * 关注用户，将数据写入MongoDB并保存至redis
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
//        判断参数的健壮性
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
//          判断用户是否已经关注了目标用户，如果已经关注则直接返回false
        if (this.isFollowUser(userId, followUserId)) {
            return false;
        }
//        在MongoDB中写入关注数据
        FollowUser followUser = new FollowUser();
        followUser.setId(ObjectId.get());
        followUser.setUserId(userId);
        followUser.setFollowUserId(followUserId);
        followUser.setCreated(System.currentTimeMillis());
        FollowUser user = this.mongoTemplate.save(followUser);
//        如果存入MongoDB成功，则将数据以hash的类型再保存至redis
        if (ObjectUtil.isNotEmpty(user)) {
//            编辑redisKey
            String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
//            编辑hashKey
            String hashKey = String.valueOf(followUserId);
//            "1"表示关注了
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        }

        return false;
    }

    /**
     * 取关用户
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        //        判断参数的健壮性
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
//              没有关注过则返回false
        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }

        //取消关注，删除关注数据即可
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
//        如果MongoDB中的关注数据删除成功
        if (result.getDeletedCount() > 0) {
            //同时删除redis中的数据
            String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);

            return true;
        }

        return false;
    }

    /**
     * 判断用户是否关注某用户，查询redis判断
     *
     * @param userId
     * @param followUserId
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        //        判断参数的健壮性
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        String redisKey = VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
        String hashKey = String.valueOf(followUserId);
//        判断redis中是否存在该hash数据
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }


}
